import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/register', '/', "/ProductDisplay", "/ShoppingCart"]

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    /* 下一行在设置网页的标题*/
    //to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    if (to.meta.title) {
      document.title = to.meta.title
    }
    /* has token*/
    if (to.path === '/login') {
      /** 下一行意思是在已登陆的状态下访问了登录页的话，直接导向path: '/' */
      next({ path: '/User_Portal' })
      NProgress.done()
    } else {
      // 判断当前用户是否已拉取完user_info信息
      if (store.getters.email.length === 0) {
        store.dispatch('GetInfo').then(() => {
          next()
        }).catch(err => {
            store.dispatch('LogOut').then(() => {
              Message.error(err)
              next({ path: '/login' })
            })
          })
      } else {
        next()
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
